//在页面加载完成以后加载
$(function () {
    //设置浏览器窗口显示文字
    $("#title").text("SignIn");
    //加载动画
    let html = "<div class=\"spinner\">\n" +
        "  <div class=\"spinner-container container1\">\n" +
        "    <div class=\"circle1\"></div>\n" +
        "    <div class=\"circle2\"></div>\n" +
        "    <div class=\"circle3\"></div>\n" +
        "    <div class=\"circle4\"></div>\n" +
        "  </div>\n" +
        "  <div class=\"spinner-container container2\">\n" +
        "    <div class=\"circle1\"></div>\n" +
        "    <div class=\"circle2\"></div>\n" +
        "    <div class=\"circle3\"></div>\n" +
        "    <div class=\"circle4\"></div>\n" +
        "  </div>\n" +
        "  <div class=\"spinner-container container3\">\n" +
        "    <div class=\"circle1\"></div>\n" +
        "    <div class=\"circle2\"></div>\n" +
        "    <div class=\"circle3\"></div>\n" +
        "    <div class=\"circle4\"></div>\n" +
        "  </div>\n" +
        "</div>"
    //获取json文件中的内容
    $.getJSON('../public/port/ControllerPort.json', function (data) {
        //获取请求url路径
        let url = data.Url + ':' + data.Port + '/' + data.ProjectName + '/' + data.LoginController + '/signIn';
        //vue逻辑
        let app = new Vue({
                //vue操作的区域
                el: "#login",
                data: {
                    //用户名提示信息
                    UsernameMessage: "用户名长度为4～18个字符、只能以字母开头、数字、点、减号或下划线组成",
                    //密码提示信息
                    PasswordMessage: "密码长度为4～10个字符、由任意字符组成",
                    //记住登录的账户与密码
                    RememberMessage: "将会保存您的登录信息",
                    //用户输入的账户名
                    Username: "",
                    //用户输入的密码
                    Password: "",
                    //账户名框内提示文字
                    UsernamePlaceholder: "username",
                    //密码框内提示文字
                    PasswordPlaceholder: "password",
                    //账户名外框style风格
                    UsernameStyle: {},
                    //密码外框style风格
                    PasswordStyle: {},
                    //单选框状态
                    CheckStatus: false,
                    //加载状态
                    LoadingStatus: "",
                    LoadingColor: {
                        color: "red"
                    },
                    eventname: "click"
                },
                methods: {
                    //登录方法
                    login: function () {
                        //获取当前vue中绑定的用户输入的数据
                        let Username = this.Username;
                        let Password = this.Password;
                        //用户名正则表达式验证
                        let patten = /^[a-zA-Z]\w{3,15}$/ig;
                        //判断用户名
                        if (Username === "" || Username == null) {
                            app.UsernamePlaceholder = "请填写账户名";
                            app.UsernameStyle.border = "1px solid #a94442";
                            app.CheckStatus = false;
                            removeCookie();
                            return;
                        } else if (!patten.test(Username)) {
                            app.Username = "";
                            app.UsernamePlaceholder = "账户名不合法";
                            app.UsernameStyle.border = "1px solid #a94442";
                            app.CheckStatus = false;
                            removeCookie();
                            return;
                        } else {
                            app.UsernameStyle.border = null;
                            app.UsernamePlaceholder = "username";
                        }
                        //密码正则表达式验证
                        let patten2 = /^\S{4,10}$/;
                        //判断密码
                        if (Password === "" || Password == null) {
                            app.PasswordPlaceholder = "请填写密码";
                            app.PasswordStyle.border = "1px solid #a94442";
                            app.CheckStatus = false;
                            removeCookie();
                            return;
                        } else if (!patten2.test(Password)) {
                            app.Password = "";
                            app.PasswordPlaceholder = "密码不合法";
                            app.PasswordStyle.border = "1px solid #a94442";
                            app.CheckStatus = false;
                            removeCookie();
                            return;
                        } else {
                            app.PasswordStyle.border = null;
                            app.PasswordPlaceholder = "password";
                        }
                        //判断没有错误信息的情况下发送请求
                        if (app.PasswordPlaceholder === "password" && app.UsernamePlaceholder === "username") {
                            $("#loading").css("display", "");
                            $.ajax({
                                url: url,
                                data: {
                                    username: Username,
                                    password: Password
                                },
                                type: "post",
                                dataType: "json",
                                timeout: 5000,
                                success: function (data) {
                                    //判断当响应成功并信息无误跳转到登录
                                    if (data.code === 200 && data.message === "登录成功") {
                                        //设置加载图标延时显示
                                        setTimeout(function () {
                                            $("#loading").css("display", "none");
                                        }, 1000);
                                        app.LoadingStatus = null;
                                        //登录成功后如用户点击了"记住我"的选项将会保存cookie以便下次登录
                                        if (app.CheckStatus === true) {
                                            $.cookie("user", Username, {expires: 1, path: '/'});
                                            //加密密码
                                            $.cookie("pass", $.base64.encode(Password), {expires: 1, path: '/'});
                                        } else {
                                            removeCookie();
                                        }
                                        window.location.replace("index.html");
                                    } else {
                                        console.log(data)
                                        if (data.state >= 3 && data.message === "登录失败") {
                                            $("#signIn").css("display", "none");
                                            $("#verification").css("display", "block");
                                        }
                                        if (data.code === 401 && data.data === "用户名不存在") {
                                            //设置加载图标延时显示
                                            setTimeout(function () {
                                                app.LoadingStatus = null;
                                                $("#loading").css("display", "none");
                                            }, 900);
                                            app.UsernamePlaceholder = data.data;
                                            app.UsernameStyle.border = "1px solid #a94442";
                                            app.Username = null;
                                            app.Password = null;
                                            app.PasswordPlaceholder = "password";
                                            app.CheckStatus = false;
                                            removeCookie();
                                        } else if (data.code === 401 && data.data === "Bad credentials") {
                                            //设置加载图标延时显示
                                            setTimeout(function () {
                                                app.LoadingStatus = null;
                                                $("#loading").css("display", "none");
                                            }, 900);
                                            app.Password = "";
                                            app.PasswordStyle.border = "1px solid #a94442";
                                            app.PasswordPlaceholder = "密码错误";
                                            app.CheckStatus = false;
                                            removeCookie();
                                        } else if (data.message === "登录失败") {
                                            $("#loading").css("display", "none");
                                            app.LoadingStatus = "请求失败  (request was aborted)";
                                        }
                                    }
                                }, error: function (jqXHR, textStatus) {
                                    console.log(textStatus)
                                    if (textStatus === "error" || textStatus === "timeout") {
                                        $("#loading").css("display", "none");
                                        app.LoadingStatus = "请求超时  (request timeout)";
                                    }
                                }
                            });

                        }
                    },
                    SlidingVerificationCode: function () {
                        //获取请求url路径
                        let url = data.Url + ':' + data.Port + '/' + data.ProjectName + '/' + data.VerificationController + '/Image';
                        let open = layer.open({
                            id: 3,
                            offset: 'center',
                            height: '265px',
                            area: ['461px', '345px'],
                            type: 1,
                            title: '图形验证',
                            anim: Math.ceil(Math.random() * 6),
                            resize: false,
                            move: false,
                            content:
                                '<br/><div class="verBox" style="height: 265px;width: 450px;text-align:center"><div id="loadings"></div>'
                                + '<div id="imgVer" style="display:inline-block;"></div>'
                                + '</div>',
                            success: function () {
                                let loadings = $("#loadings");
                                SpinnerContainerStyle("spinner-container", "display", "block");
                                loadings.html(html);
                                $.ajax({
                                    url: url,
                                    data: {},
                                    type: "Post",
                                    success: function (data) {
                                        SpinnerContainerStyle("spinner-container", "display", "none");
                                        app.LoadingStatus = null;
                                        var SrcImage = "data:image/jpg;base64," + data.SrcImage
                                        var CutImage = "data:image/jpg;base64," + data.CutImage
                                        var YPosition = data.YPosition
                                        var SrcImageWidth = data.SrcImageWidth;
                                        var SrcImageHeight = data.SrcImageHeight;
                                        imgVer({
                                            el: '$("#imgVer")',
                                            width: '220',
                                            height: '116',
                                            SrcImage: SrcImage,
                                            CutImage: CutImage,
                                            YPosition: YPosition,
                                            SrcImageWidth: SrcImageWidth,
                                            SrcImageHeight: SrcImageHeight,
                                            success: function () {
                                                //验证成功可自定义后续逻辑
                                                setTimeout(function () {
                                                    layer.closeAll();
                                                    $("#signIn").css("display", "block");
                                                    $("#verification").css("display", "none");
                                                }, 1350)
                                            }
                                        });
                                    }, error: function () {
                                        layer.close(open);
                                        SpinnerContainerStyle("spinner-container", "display", "none");
                                        app.LoadingStatus = "请求超时  (request timeout)";
                                    }
                                });
                            }
                        });
                    }
                }
            })
        ;
        //触发滑动验证码
        $("#verification").click(function () {
            app.SlidingVerificationCode();
        })
        //获取浏览器cookie信息
        let user = $.cookie('user');
        let pass = $.cookie("pass");
        //当浏览器中有cookie信息将会直接设置到输入框中
        if (user !== undefined && pass !== undefined) {
            app.Username = user;
            //解密密码
            app.Password = $.base64.decode(pass);
            app.CheckStatus = true;
        }


        //删除cookie方法
        function removeCookie() {
            $.removeCookie('user', {path: '/'});
            $.removeCookie('pass', {path: '/'});
        }

        function detectmob() {
            return !!(navigator.userAgent.match(/Android/i)
                || navigator.userAgent.match(/webOS/i)
                || navigator.userAgent.match(/iPhone/i)
                || navigator.userAgent.match(/iPad/i)
                || navigator.userAgent.match(/iPod/i)
                || navigator.userAgent.match(/BlackBerry/i)
                || navigator.userAgent.match(/Windows Phone/i));
        }

        function imgVer(Config) {
            var el = eval(Config.el);
            var w = Config.width;
            var h = Config.height;
            var SrcImage = Config.SrcImage
            var CutImage = Config.CutImage
            var YPosition = Config.YPosition
            var SrcImageHeight = Config.SrcImageHeight;
            var SrcImageWidth = Config.SrcImageWidth;
            var wbili = w / SrcImageWidth;
            var hbili = h / SrcImageHeight;
            var padding = 20;
            var imgSrc = SrcImage;
            var left_Num = 0;
            var htmls = '<div style="position:relative;padding:16px 16px 28px;border:1px solid #ddd;background:#f8f8f8;border-radius:16px;">';
            htmls += '<div style="position:relative;overflow:hidden;width:' + w + 'px;">';
            htmls += '<div style="position:relative;width:' + w + 'px;height:' + h + 'px;">';
            htmls += '<img id="scream" src="' + imgSrc + '" style="width:' + w + 'px;height:' + h + 'px;" alt="">';
            htmls += '<canvas id="puzzleBox" width="' + w + '" height="' + h + '" style="position:absolute;left:0;top:0;z-index:22;"></canvas>';
            htmls += '</div>';
            htmls += '<div class="puzzle-lost-box" style="position:absolute;width:' + w + 'px;height:' + h + 'px;top:0;left:' + left_Num + 'px;z-index:111;">';
            htmls += '<canvas id="puzzleShadow" width="' + w + '" height="' + h + '" style="position:absolute;left:0;top:0;z-index:22;"></canvas>';
            htmls += '<canvas id="puzzleLost" width="' + w + '" height="' + h + '" style="position:absolute;left:0;top:0;z-index:33;"></canvas>';
            htmls += '</div>';
            htmls += '<p class="ver-tips"></p>';
            htmls += '</div>';
            htmls += '<div class="re-btn"><a></a></div>';
            htmls += '</div>';
            htmls += '<br>';
            htmls += '<div style="position:relative;width:' + w + 'px;margin:auto;touch-action: pan-y">';    //设置触摸区域，防止左滑返回
            htmls += '<div style="border:1px solid #c3c3c3;border-radius:24px;background:#f8f8f8;box-shadow:0 1px 1px rgba(12,10,10,0.2) inset;">';
            htmls += '<p style="font-size:12px;color: #4c7186;line-height:28px;margin:0;text-align:right;padding-right:22px;">按住滑块 拖动完成上方拼图</p>';
            htmls += '</div>';
            htmls += '<div class="slider-btn"></div>';
            htmls += '</div>';
            el.html(htmls);
            var c_l = document.getElementById("puzzleLost");
            var ctx_l = c_l.getContext("2d");
            var img = new Image();
            img.src = CutImage;
            img.onload = function () {
                ctx_l.drawImage(img, 0, YPosition * hbili, 50 * wbili, 50 * hbili);
            }
            //刷新验证码
            $(".re-btn a").on('click', function () {
                Refresh_VerifyButton();
            })
            var moveStart = '';
            let SliderBtn = $(".slider-btn");
            let PuzzleLost = $("#puzzleLost");
            let PuzzleShadow = $("#puzzleShadow");
            if (detectmob()) {
                //Mobile端
                document.getElementsByClassName('slider-btn')[0].addEventListener("touchstart", function (e) {
                    e = e || event;
                    $(this).css({"background-position": "0 -216px"});
                    moveStart = e.touches[0].pageX;
                }, false);
                var moveEnd;
                document.addEventListener("touchmove", function (e) {
                    e = e || event;
                    var moveX = e.touches[0].pageX;
                    var d = moveX - moveStart;
                    if (moveStart !== '') {
                        // eslint-disable-next-line no-empty
                        if (d < 0 || d > (w - 2 * padding)) {

                        } else {
                            SliderBtn.css({"left": d + 'px', "transition": "inherit"});
                            PuzzleLost.css({"left": d + 'px', "transition": "inherit"});
                            PuzzleShadow.css({"left": d + 'px', "transition": "inherit"});
                        }
                    }
                    moveEnd = moveX
                }, false);
                document.addEventListener("touchend", function (e) {
                    e = e || event;
                    var moveEnd_X = moveEnd - moveStart;
                    if (moveStart !== '') {
                        CheckResult_VerifyButton(moveEnd_X, wbili, Config);
                    }
                    setTimeout(function () {
                        SliderBtn.css({"left": '0', "transition": "left 0.5s"});
                        PuzzleLost.css({"left": '0', "transition": "left 0.5s"});
                        PuzzleShadow.css({"left": '0', "transition": "left 0.5s"});
                    }, 1000);
                    SliderBtn.css({"background-position": "0 -84px"});
                    moveStart = '';
                    Refresh_VerifyButton();
                }, false)
            } else {    //PC端
                SliderBtn.mousedown(function (e) {
                    e = e || event;
                    $(this).css({"background-position": "0 -216px"});
                    moveStart = e.pageX;
                });
                let moveEnd;
                onmousemove = function (e) {
                    e = e || event;
                    var moveX = e.pageX;
                    var d = moveX - moveStart;
                    if (moveStart !== '') {
                        // eslint-disable-next-line no-empty
                        if (d < 0 || d > (w - 2 * padding)) {

                        } else {
                            SliderBtn.css({"left": d + 'px', "transition": "inherit"});
                            PuzzleLost.css({"left": d + 'px', "transition": "inherit"});
                            PuzzleShadow.css({"left": d + 'px', "transition": "inherit"});
                        }
                    }
                    moveEnd = moveX
                };
                onmouseup = function (e) {
                    e = e || event;
                    var moveEnd_X = e.pageX - moveStart;
                    if (moveStart !== '') {
                        CheckResult_VerifyButton(moveEnd_X, wbili, Config);
                    }
                    setTimeout(function () {
                        SliderBtn.css({"left": '0', "transition": "left 0.5s"});
                        PuzzleLost.css({"left": '0', "transition": "left 0.5s"});
                        PuzzleShadow.css({"left": '0', "transition": "left 0.5s"});
                    }, 1000);
                    SliderBtn.css({"background-position": "0 -84px"});
                    moveStart = '';
                }
            }
        }

        function CheckResult_VerifyButton(moveEnd_X, wbili, Config) {
            let loadings = $("#loadings");
            SpinnerContainerStyle("spinner-container", "display", "block");
            loadings.html(html);
            //获取请求url路径
            let url = data.Url + ':' + data.Port + '/' + data.ProjectName + '/' + data.VerificationController + '/VerifyImage';
            $.ajax({
                url: url,
                data: {
                    x: $.base64.encode(moveEnd_X),
                    y: $.base64.encode(wbili)
                },
                type: "POST",
                success: function (data) {
                    let verTips = $(".ver-tips");
                    if (data.success) {
                        app.LoadingStatus = "";
                        verTips.html('<i style="background-position:-4px -1207px;"></i><span style="color:#42ca6b;">验证通过</span><span></span>');
                        verTips.addClass("slider-tips");
                        $(".puzzle-lost-box").addClass("hidden");
                        $("#puzzleBox").addClass("hidden");
                        setTimeout(function () {
                            verTips.removeClass("slider-tips");
                            imgVer(Config);
                            SpinnerContainerStyle("spinner-container", "display", "none");
                            layer.closeAll();
                            $("#signIn").css("display", "block");
                            $("#verification").css("display", "none");
                        }, 1300);
                        Config.success();
                    } else {
                        app.LoadingStatus = "";
                        verTips.html('<i style="background-position:-4px -1229px;"></i><span style="color:red;">验证失败</span><span style="margin-left:4px;">拖动滑块将悬浮图像正确拼合</span>');
                        verTips.addClass("slider-tips");
                        setTimeout(function () {
                            verTips.removeClass("slider-tips");
                            SpinnerContainerStyle("spinner-container", "display", "none");
                        }, 1300);
                    }
                }
            })
        }

        function SpinnerContainerStyle(Object, Attribute, Style) {
            $("." + Object).css(Attribute, Style);
        }

        function Refresh_VerifyButton() {
            let loadings = $("#loadings");
            loadings.html(html);
            SpinnerContainerStyle("spinner-container", "display", "block");
            //获取请求url路径
            let url = data.Url + ':' + data.Port + '/' + data.ProjectName + '/' + data.VerificationController + '/Image';
            $.ajax({
                url: url,
                data: {},
                cache: false,
                type: "POST",
                success: function (data) {
                    var SrcImage = "data:image/jpg;base64," + data.SrcImage
                    var CutImage = "data:image/jpg;base64," + data.CutImage
                    var YPosition = data.YPosition
                    var SrcImageWidth = data.SrcImageWidth;
                    var SrcImageHeight = data.SrcImageHeight;
                    setTimeout(function () {
                        SpinnerContainerStyle("spinner-container", "display", "none");
                    }, 1000)
                    imgVer({
                        el: '$("#imgVer")',
                        width: '220',
                        height: '116',
                        SrcImage: SrcImage,
                        CutImage: CutImage,
                        YPosition: YPosition,
                        SrcImageWidth: SrcImageWidth,
                        SrcImageHeight: SrcImageHeight,
                        success: function () {
                            app.LoadingStatus = null;
                            SpinnerContainerStyle("spinner-container", "display", "none");
                        },
                        error: function () {
                            app.LoadingStatus = null;
                            SpinnerContainerStyle("spinner-container", "display", "none");
                        }
                    });
                },
                error: function () {
                    SpinnerContainerStyle("spinner-container", "display", "none");
                    app.LoadingStatus = "请求超时  (request timeout)";
                }
            });
        }
    });
});